package br.usp.ime.components;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;

/**
 * This class is used to collect information about the host where the application is located
 *
 */
@Component
@ApplicationScoped
public class UnixCommands {

	public boolean dnsDomainNameIs(String dnsDomainName) {
		return dnsDomainName.equals(getDnsDomainName());
	}
	
	/**
	 * The host doesn't have the unix command dnsdomainname, the function return null
	 * If it has, then return the dns domain name of it.
	 */
	private static String getDnsDomainName() {
		String output;
		try {
			output = getDnsDomainNameWithoutTryCatch();
		} catch (IOException e) {
			output = null;
		}
		return output;
	}

	/**
	 * Execute the unix command "dnsdomainname" to get the dns domain name of the host
	 * if this command does not exist in the host, the function thrwos an exception
	 * if it has, it returns the returned value of this command
	 * @return
	 * @throws IOException
	 */
	private static String getDnsDomainNameWithoutTryCatch() throws IOException {
		String s, output = null;
		Process p = Runtime.getRuntime().exec("dnsdomainname");
		BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
		BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
		
		while((s = stdInput.readLine()) != null) {
			output = s;
		}
		
		while((s = stdError.readLine()) != null) {
			output = s;
		}
		return output;
	}

}
